package com.modelscope.ai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.modelscope.ai.domain.entity.ArticleItem;
import com.modelscope.ai.domain.entity.Exam;
import com.modelscope.ai.domain.entity.ExamItem;
import com.modelscope.ai.domain.entity.User;
import com.modelscope.ai.mapper.*;
import com.modelscope.ai.service.ExamItemService;
import com.modelscope.ai.utils.AssertUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * @author Administrator
 * @description 针对表【exam_item】的数据库操作Service实现
 * @createDate 2024-03-17 21:46:13
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class ExamItemServiceImpl extends ServiceImpl<ExamItemMapper, ExamItem> implements ExamItemService {


    final ExamMapper examMapper;
    final ArticleItemMapper articleItemMapper;
    final ArticleMapper articleMapper;
    final UserMapper userMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(Long uid, Long articleItemId, Integer score, String content) {
        log.info("uid:{},articleItemId:{},score:{},content:{}", uid, articleItemId, score, content);
        // 首先得判断一下 uid 是否存在
        User user = userMapper.selectById(uid);
        AssertUtil.isNotEmpty(user, "用户id不存在");
        ArticleItem articleItem = articleItemMapper.selectById(articleItemId);
        AssertUtil.isNotEmpty(articleItem, "文章id不存在");
        // 首先，根据用户id 和 题目id 来查找 题目是否已经存储
        Exam exam = examMapper.selectOne(new LambdaQueryWrapper<Exam>().eq(Exam::getUid, uid).eq(Exam::getArticleId, articleItem.getPid()));
        // 如果试卷不存在，则创建
        if (Objects.isNull(exam)) {
            exam = new Exam();
            exam.setUid(uid);
            exam.setScore(0.0);
            exam.setArticleId(articleItem.getPid());
            examMapper.insert(exam);
        }
        // 这边保存考试成绩
        ExamItem one = lambdaQuery().eq(ExamItem::getPid, exam.getId()).eq(ExamItem::getArticleitemId, articleItemId).one();
        if (Objects.isNull(one)) {
            one = new ExamItem();
            one.setPid(exam.getId());
            one.setContent(content);
            one.setScore(score * 1.0);
            one.setArticleitemId(articleItemId);
        } else {
            one.setScore(score * 1.0);
            one.setContent(content);
        }
        saveOrUpdate(one);
    }
}




